'use client';
import Image from 'next/image';
import Slider from 'react-slick';
import 'slick-carousel/slick/slick.css';
// import 'slick-carousel/slick/slick-theme.css';
import './CustomCarousel.scss';
import { useEffect, useRef, useState } from 'react';
import Lightbox from 'react-image-lightbox';
import 'react-image-lightbox/style.css';
import MyImage from '@/components/MyImage';

const CustomNextArrow = (props: any) => {
  const { className, style, onClick } = props;
  return (
    <div className={className} onClick={onClick} style={{ ...style }}>
      <div className="iconfont icon-forward-line"></div>
    </div>
  );
};
const CustomPrevArrow = (props: any) => {
  const { className, style, onClick } = props;
  return (
    <div className={className} onClick={onClick} style={{ ...style }}>
      <div className="iconfont icon-back-line"></div>
    </div>
  );
};
type ThisProps = {
  imgList: string[];
};
const CustomCarousel = ({ imgList: imgListProps }: ThisProps) => {
  const [imgList, setImgList] = useState<string[]>(imgListProps);

  const handleNewSrc = (nsrc: string, index: number) => {
    const newImgList = [...imgList];
    newImgList[index] = nsrc;
    setImgList(newImgList);
  };
  //==========================================================
  const containerRef = useRef(null);
  // const [containerWidth, setContainerWidth] = useState(200);
  // //==========================================================
  // useEffect(() => {
  //   if (!containerRef.current) return;
  //   const resizeObserver = new ResizeObserver(entries => {
  //     for (const entry of entries) {
  //       setContainerWidth(entry.contentRect.width);
  //     }
  //   });
  //   resizeObserver.observe(containerRef.current);
  //   return () => {
  //     resizeObserver.disconnect();
  //   };
  // }, []);
  //==========================================================
  const [openDetail, setOpenDetail] = useState(false);
  const [currentImageIndex, setCurrentImageIndex] = useState(0);
  const [nav1, setNav1] = useState<Slider>();
  const [nav2, setNav2] = useState<Slider>();
  const sliderRef1 = useRef<any>(null);
  const sliderRef2 = useRef<any>(null);
  useEffect(() => {
    setNav1(sliderRef1.current);
    setNav2(sliderRef2.current);
  }, [sliderRef1, sliderRef2]);
  //==========================================================
  const maxThumb = 5;
  const largeSettings = {
    slidesToShow: 1,
    slidesToScroll: 1,
    arrows: false,
    infinite: imgList?.length > 1 ? true : false,
    // infinite: false,
  };
  const thumbSettings = {
    slidesToShow: maxThumb,
    swipeToSlide: true,
    focusOnSelect: true,
    infinite: imgList?.length > maxThumb ? true : false,
    // infinite: false,
    nextArrow: <CustomNextArrow />,
    prevArrow: <CustomPrevArrow />,
  };

  const handleClickLargeImage = (index: number) => {
    setCurrentImageIndex(index);
    setOpenDetail(true);
  };

  return (
    <div className="product-carousel" ref={containerRef}>
      <div className="product-carousel-large-wrapper">
        <Slider
          className="product-carousel-large"
          asNavFor={nav2}
          ref={sliderRef1}
          {...largeSettings}
        >
          {imgList.map((src, index) => (
            <div key={src} className="product-carousel-item">
              <div
                className="product-carousel-img"
                // style={{ height: containerWidth }}
                style={{ width: '100%', height: 0, paddingBottom: '100%' }}
              >
                <MyImage
                  alt=""
                  src={src}
                  // style={{width:containerWidth,height:containerWidth}}
                  fill={true}
                  // sizes={`${containerWidth}px`}
                  sizes={'500px'}
                  priority={index === 0}
                  onNewSrc={(src: string) => {
                    handleNewSrc(src, index);
                  }}
                  onClick={() => handleClickLargeImage(index)}
                />
              </div>
            </div>
          ))}
        </Slider>
        <div className="product-carousel-large-cover">
          <span className="iconfont icon-zoom_in"></span>
        </div>
      </div>
      <Slider
        className={
          'product-carousel-thumb' +
          (imgList?.length <= maxThumb ? ' product-carousel-lock' : '')
        }
        asNavFor={nav1}
        ref={sliderRef2}
        {...thumbSettings}
      >
        {imgList.map((src, index) => (
          <div key={src} className="product-carousel-item">
            <div
              className="product-carousel-img"
              // style={{ height: containerWidth / maxThumb - 8 }}
              style={{ width: '100%', height: 0, paddingBottom: '100%' }}
            >
              <MyImage
                alt=""
                src={src}
                fill={true}
                // sizes={`${containerWidth / maxThumb - 8}px`}
                sizes={'100px'}
                priority={index < 5}
              />
            </div>
          </div>
        ))}
      </Slider>

      {openDetail && (
        <Lightbox
          mainSrc={imgList[currentImageIndex]}
          nextSrc={imgList[(currentImageIndex + 1) % imgList.length]}
          prevSrc={
            imgList[(currentImageIndex + imgList.length - 1) % imgList.length]
          }
          onCloseRequest={() => setOpenDetail(false)}
          onMovePrevRequest={() =>
            setCurrentImageIndex(
              (currentImageIndex + imgList.length - 1) % imgList.length
            )
          }
          onMoveNextRequest={() =>
            setCurrentImageIndex((currentImageIndex + 1) % imgList.length)
          }
        />
      )}
    </div>
  );
};

export default CustomCarousel;
